# -*- coding: utf-8 -*-
import os
from chee import *
############################################################################
class FileHelper(object):
    def getFolder(self,urlArray):
        if len(urls) > 0: return '/'.join(urlArray)
        return '/'
    def getFolderAbs(self,urlArray):
        path = base_path
        for sub in urlArray:
            if not sub: continue
            path = os.path.join(path,sub)
        return path
    def getTempFolder(self):
        _folder = '/'.join(['static','data','temp'])
        return _folder
    def getTempFolderAbs(self):
        _folder = os.path.join(base_path, 'static','data','temp')
        return _folder
    def getSwfFolder(self):
        _folder = '/'.join(['static','data','swf'])
        return _folder
    def getSwfFolderAbs(self):
        _folder = os.path.join(base_path, 'static','data','swf')
        return _folder
    def getPayFolder(self):
        _folder = '/'.join(['static','data','pay'])
        return _folder
    def getPayFolderAbs(self):
        _folder = os.path.join(base_path, 'static','data','pay')
        return _folder
    def getHumanFolder(self,human_id):
        # 3层目录下是人物目录, 每个目录下200文件夹或文件
        file_count = 200
        total = human_id
        dirs = []
        dirs.append(total / (file_count**3))
        total = total % (file_count**3)
        dirs.append(total / (file_count**2))
        total = total % (file_count**2)
        dirs.append(total / file_count)
        human_folder = '/'.join(['static','data','human',str(dirs[0]),str(dirs[1]),str(dirs[2])])
        return human_folder
    def getHumanFolderAbs(self,human_id):
        # 3层目录下是人物目录, 每个目录下200文件夹或文件
        file_count = 200
        total = human_id
        dirs = []
        dirs.append(total / (file_count**3))
        total = total % (file_count**3)
        dirs.append(total / (file_count**2))
        total = total % (file_count**2)
        dirs.append(total / file_count)
        short_human_folder = os.path.join(str(dirs[0]),str(dirs[1]),str(dirs[2]))
        human_folder = os.path.join(base_path, 'static','data','human',short_human_folder)
        return human_folder
class ImageHelper(object):
    def getCropBox(self,orig_width,orig_height,new_width,new_height,position='center'):
        position = position.lower()
        if new_width > orig_width: new_width = orig_width
        if new_height > orig_height: new_height = orig_height
        if position in ['topleft','leftop']: return (0,0,new_width,new_height)
        elif position in ['topright','righttop']: return (orig_width-new_width,0,orig_width,new_height)
        elif position in ['bottomleft','lefbottom']: return (0,orig_height-new_height,new_width,orig_height)
        elif position in ['bottomright','rightbottom']: return (orig_width-new_width,orig_height-new_height,orig_width,orig_height)
        elif position in ['left']: return (0,(orig_height-new_height)/2,new_width,(orig_height+new_height)/2)
        elif position in ['right']: return (orig_width-new_width,(orig_height-new_height)/2,orig_width,(orig_height+new_height)/2)
        elif position in ['top']: return ((orig_width-new_width)/2,0,(orig_width+new_width)/2,new_height)
        elif position in ['bottom']: return ((orig_width-new_width)/2,orig_height-new_height,(orig_width+new_width)/2,orig_height)
        elif position in ['center']: return ((orig_width-new_width)/2,(orig_height-new_height)/2,(orig_width+new_width)/2,(orig_height+new_height)/2)
        else: return (0,0,0,0)
    def cropImage(self,folder,orig_file,new_name,width,height,position='center'):
        import Image
        my_img = None
        try: my_img = Image.open(os.path.join(folder, orig_file))
        except: pass
        if not my_img:  return u'处理图片文件出错，可能是不支持的图片文件格式!'
        my_img = my_img.convert("RGB", dither=Image.NONE, palette=Image.ADAPTIVE)
        (orig_width,orig_height) = my_img.size
        format = my_img.format
        if format == 'BMP': format = 'JPEG'
        crop_box = self.getCropBox(orig_width, orig_height, width, height, position)
        crop_img = my_img.crop(crop_box)
        crop_img.save(os.path.join(folder, new_name),format,quality=96)
        return u''
    def resizeImage(self,folder,orig_file,new_name,width,height):
        import Image
        my_img = None
        try: my_img = Image.open(os.path.join(folder, orig_file))
        except: pass
        if not my_img:  return u'处理图片文件出错，无法打开文件!'
        my_img = my_img.convert("RGB", dither=Image.NONE, palette=Image.ADAPTIVE)
        format = my_img.format
        if format == 'BMP': format = 'JPEG'
        my_img = my_img.resize((width,height), Image.ANTIALIAS)
        my_img.save(os.path.join(folder, new_name),format,quality=96)
        return u''
    def cutImage(self,folder,up_file,cut_files,filters=['.jpg','.bmp','.gif','.png']):
        ''' cut_files format:[{'prefix/name':'','width':0,'height':0,'type':'resize/crop/copy','position':'center/..'}...]
        '''
        retString = u''
        if not up_file: return {'filename':'','result':u'没有文件'}
        (fname,suffix) = os.path.splitext(up_file.filename)
        suffix = suffix.lower()
        if suffix not in filters: return {'filename':'','result':u'请上传图片文件，支持%s格式' % ('/'.join(filters))}
        if not os.path.exists(folder): os.makedirs(folder) 
        from chee.util import getRandomName
        only_file_name = getRandomName(); save_file_name = only_file_name + suffix
        f = open(os.path.join(folder, save_file_name), 'wb')
        while True:
            s = up_file.read(10 ** 6)
            if s: f.write(s)
            else: f.close(); break
        for item in cut_files:
            i_name = 't_' + save_file_name
            if item.has_key('prefix'): i_name = item['prefix'] + save_file_name
            elif item.has_key('name'): i_name = item['name'] + suffix
            cut_type = 'resize'
            if item.has_key('type'): cut_type = item['type']
            cut_type = cut_type.lower()
            if cut_type == 'resize': 
                resz = self.resizeImage(folder, save_file_name, i_name, item['width'], item['height'])
                if resz: retString += u'生成%s失败，原因是：%s \n' % (i_name,resz)
            elif cut_type == 'crop':
                cut_pos = 'center'
                if item.has_key('position'): cut_pos = item['position'] 
                crop = self.cropImage(folder, save_file_name, i_name, item['width'], item['height'], cut_pos)
                if crop: retString += u'生成%s失败，原因是：%s \n' % (i_name,crop)
            elif cut_type == 'copy':
                import shutil
                shutil.copy(os.path.join(folder,save_file_name), os.path.join(folder,i_name))
        return {'filename':save_file_name,'result':retString}
    def reduce_opacity(self,im, opacity):
        import Image, ImageEnhance
        """Returns an image with reduced opacity."""
        assert opacity >= 0 and opacity <= 1
        if im.mode != 'RGBA': im = im.convert('RGBA')
        else: im = im.copy()
        alpha = im.split()[3]
        alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
        im.putalpha(alpha)
        return im
    def watermark(self,imagefile,markfile,opacity=1,padding=50,save_to=None,position='bottom_right'):
        import Image, ImageEnhance
        """Adds a watermark to an image."""   
        im = Image.open(imagefile)
        mark = Image.open(markfile)   
        if opacity < 1: mark = reduce_opacity(mark, opacity)
        if im.mode != 'RGBA': im = im.convert('RGBA')
        # create a transparent layer the size of the image and draw the
        # watermark in that layer.
        layer = Image.new('RGBA', im.size, (0,0,0,0))
        if position == 'title':
            for y in range(0, im.size[1], mark.size[1]):
                for x in range(0, im.size[0], mark.size[0]):
                    layer.paste(mark, (x, y))
        elif position == 'scale':
            # scale, but preserve the aspect ratio
            ratio = min(float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
            w = int(mark.size[0] * ratio)
            h = int(mark.size[1] * ratio)
            mark = mark.resize((w, h))
            layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
        elif position == 'top_left':
            #top_left
            position = (padding,padding)
            layer.paste(mark, position)
        elif position == 'top_right':
            #top_right
            position = (im.size[0] - mark.size[0]-padding, padding)
            layer.paste(mark, position)
        elif position == 'center':
            #center
            position = ((im.size[0] - mark.size[0])/2,(im.size[1] - mark.size[1])/2)
            layer.paste(mark, position)
        elif position == 'bottom_left':
            #bottom_left
            position = (padding,im.size[1] - mark.size[1]-padding,)
            layer.paste(mark, position)
        else:
            # bottom_right  (default)
            position = (im.size[0] - mark.size[0]-padding, im.size[1] - mark.size[1]-padding,)
            layer.paste(mark, position)
        # composite the watermark with the layer
        result = Image.composite(layer, im, layer)
        if save_to == None: result.save(imagefile,quality=90)
        else: result.save(save_to,quality=90)
    
